#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#define CTRL_LED_CMD    (0x01)

char printMenu()
{
    char oper;

    do
    {
        printf("Please Select led on or off: \n"
            "\t[0] led on\n"
            "\t[1] led off\n"
            "\t[q|Q] quit appp\n");

        printf("Your selection: ");
        oper = (char)getchar();
        getchar();
        printf("\n");
        if(oper != '0' && oper != '1' 
            && oper != 'Q' && oper != 'q')
            continue;
        break;
    }while(1);

    return oper;
}

char printLedSelectMenu()
{
    char oper;
    do
    {
        printf("Please Select which led: \n"
            "\t[a|A] open /dev/led0 \n"
            "\t[b|B] open /dev/led1 \n"
            "\t[c|C] open /dev/led2 \n"
            "\t[t|T] open /dev/led3 \n"
            "\t[q|Q] quit app \n");

        printf("Your selection: ");
        oper = (char)getchar();
        getchar();
        printf("\n");
        if(oper != 'a' && oper != 'A' 
            && oper != 'b' && oper != 'B'  
            && oper != 'c' && oper != 'C'
            && oper != 't' && oper != 'T'
            && oper != 'q' && oper != 'Q')
            continue;
        break;
    }while(1);

    return oper;
}
int main(int argc,char *argv[])
{
    char *dev_name = NULL;
    char ch = printLedSelectMenu();
    switch(ch)
    {
        case 'a':
        case 'A':
            dev_name = "/dev/led0";
            break;
        case 'b':
        case 'B':
            dev_name = "/dev/led1";
            break;
        case 'c':
        case 'C':
            dev_name = "/dev/led2";
            break;
        case 't':
        case 'T':
            dev_name = "/dev/led3";
            break;
        case 'q':
        case 'Q':
            return 0;
        default:
            return 0;
    }
	int fd = open(dev_name, O_RDWR);
	if(fd < 0)
	{
		printf("open [%s] failed\n", dev_name);
		return -1;
	}
    int quitApp = 0;
    int onoff;
    do
    {
        char oper = printMenu();
        switch(oper)
        {
           case '0':
                onoff = 0;
                break;
           case '1':
                onoff = 1;
                break;
           case 'Q':
           case 'q':
                quitApp = 1;
                break;
        }
        if(quitApp)
            break;
        ioctl(fd, CTRL_LED_CMD, &onoff);
    }while(1);

	close(fd);
	return 0;
}
